
#ifndef __CE_INSTANCEDMESH_H__
#define __CE_INSTANCEDMESH_H__


#include <cegfx/ceexport.h>
#include <cegfx/cerendermesh.h>
#include <vector>


class CE_GFX_API ceInstancedMesh : public iGeometry
{
	IQF_DECLARATION;
protected:
	LPDIRECT3DVERTEXBUFFER9					vertexBuffer;
	unsigned												numVertices;
	LPDIRECT3DINDEXBUFFER9					indexBuffer;
	unsigned												numTriangles;

	LPDIRECT3DVERTEXDECLARATION9		vertexDeclaration;
	unsigned stride;

	

private:
	float														instanceRadius;

	struct Part
	{
		ceBoundingBox									bbox;
		std::vector<D3DXVECTOR4>			positions;
		std::vector<Part>							parts;
		LPDIRECT3DVERTEXBUFFER9				instanceBuffer;
	};

	Part														part;

	bool Optimize (LPDIRECT3DDEVICE9 device, Part& part);
	void UpdateBoundingBox (Part& part);
	void RenderPart (Part& part, LPDIRECT3DDEVICE9 device, ceEffect* effect, D3DXHANDLE handle, const ceClipper* clipper);

public:
	ceInstancedMesh ();
	~ceInstancedMesh ();


	void SetVertices (LPDIRECT3DVERTEXBUFFER9	vertexBuffer, unsigned numVertices);
	LPDIRECT3DVERTEXBUFFER9 GetVertexBuffer ();
	const LPDIRECT3DVERTEXBUFFER9 GetVertexBuffer () const;
	unsigned GetNumVertices () const;

	void SetVertexDeclaration (LPDIRECT3DVERTEXDECLARATION9 declaration, unsigned stride);
	LPDIRECT3DVERTEXDECLARATION9 GetVertexDeclaration ();
	const LPDIRECT3DVERTEXDECLARATION9 GetVertexDeclaration () const;
	unsigned GetStride () const;

	void SetIndices (LPDIRECT3DINDEXBUFFER9 indexBuffer, unsigned numTriangles);
	LPDIRECT3DINDEXBUFFER9 GetIndexBuffer();
	const LPDIRECT3DINDEXBUFFER9 GetIndexBuffer() const;
	unsigned GetNumberOfTriangles () const;


	void ClearInstances ();
	void AddInstance (const D3DXVECTOR3& pos);
	void SetInstanceRadius (float radius);
	bool Pack (LPDIRECT3DDEVICE9 device);
	void UpdateBoundingBox ();


	virtual void Render (const ceRenderEnv& renderEnv);
	virtual void Update (const ceUpdateEnv& updateEnv);
	const ceBoundingBox& GetBoundingBox () const;
};


#endif /* ! __CE_INSTANCEDMESH_H__ */ 
